<template>
<!-- 筛选区 -->
   <div class="sub-filter" >
     <div class="item" v-for="item in list" :key="item.id"

     >
       <div class="head">{{item.name}}:</div>
       <div class="body">
         <a href="javascript:;"
@click="getAttFn(item,{})"
          :class="{ active: item.activeName === undefined }"
         >全部</a>
         <a href="javascript:;"
          v-for="item2 in item.properties"
          :key="item2.id"
@click="getAttFn(item,item2)"
 :class="{ active: item.activeName === item2.name }"
          >{{item2.name}}</a>
       </div>
     </div>
   </div>
</template>

<script>
import { computed, inject, reactive, toRef } from 'vue'
export default {
  name: 'SubFilter',
  setup () {
    // 接收父组件传过来的数据
    const subCate = inject('subCate')
    const sortParams = inject('sortParams')
    // 💥问题修复：把品牌也定义成响应式数据，否则视图更新不同步
    const brands = reactive({ id: null, name: '品牌', properties: subCate.value.brands })
    // 先展开数据 然后把品牌的数据合并进去
    const list = computed(() => {
      return [
        //   定义id为空，name叫品牌，然后把subCate里面的原来是品牌的数据加进去
        brands,
        // 展开数据
        ...subCate.value.saleProperties
      ]
    })
    // 拿出单个
    const attrs = toRef(sortParams, 'attrs')
    // console.log(attrs)
    const brandId = toRef(sortParams, 'brandId')
    //
    const getAttFn = (theItem, theProp) => {
      theItem.activeName = theProp.name
      if (theItem.name === '品牌') {
        brandId.value = theProp.id
        return
      }
      // console.log(theItem)
      const index = attrs.value.findIndex(item => item.groupName === theItem.name)
      // console.log(theProp)

      if (index === -1) {
        attrs.value.push({ groupName: theItem.name, propertyName: theItem.activeName })
      } else {
        attrs.value[index].propertyName = theItem.activated
      }
      attrs.value = attrs.value.filter(item => item.propertyName)
    }
    // console.log(list)
    return { list, getAttFn }
  }
}
</script>

<style scoped lang='less'>
  // 筛选区
  .sub-filter {
    background: #fff;
    padding: 25px;
    .item {
      display: flex;
      line-height: 40px;
      .head {
        width: 80px;
        color: #999;
      }
      .body {
        flex: 1;
        a {
          margin-right: 36px;
          transition: all .3s;
          display: inline-block;
          &.active,
          &:hover {
            color: @xtxColor;
          }
        }
      }
    }
  }
</style>
